/* * * * M A P V I S I O N   L I C E N S E  *****************************************************************
 *
 * This MapVision software is © Filip Zavadil 2013. It is licensed under the LGPL license.
 * This MapVision software dynamically links to unmodified Qt5 Library.
 *
 * The Qt5 Library is © 2013 Qt® and/or its subsidiary(-ies), and is licensed under the
 * GNU Lesser General Public License version 2.1 with Qt® LGPL exception version 1.1.
 * Qt5 library is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License, version 2.1, as published by the Free Software Foundation.
 * Qt5 library is provided “AS IS”, without WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * As an additional permission to the GNU Lesser General Public License version 2.1, the object
 * code form of a “work that uses the Library” may incorporate material from a header file that is
 * part of the Library. You may distribute such object code under terms of your choice,
 * provided that: (i) the header files of the Library have not been modified; and (ii)
 * the incorporated material is limited to numerical parameters, data structure layouts, accessors,
 * macros, inline functions and templates; and (iii) you comply with the terms of Section 6 of the
 * GNU Lesser General Public License version 2.1.
 *
 * Moreover, you may apply this exception to a modified version of the Library, provided that such
 * modification does not involve copying material from the Library into the modified Library’s header
 * files unless such material is limited to (i) numerical parameters; (ii) data structure layouts;
 * (iii) accessors; and (iv) small macros, templates and inline functions of five lines or less in length.
 *
 * Furthermore, you are not required to apply this additional permission to a modified version of the Library.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this package;
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

 * The source code for Qt 5.X SDK is available from Qt Project here:
 * http://download.qt-project.org/official_releases/qtcreator/2.7/2.7.0/qt-creator-2.7.0-src.zip.
 *
 * ****************************** M A P V I S I O N    S O F T W A R E  ************************************
 *
 * Author:       Filip Zavadil
 * Description:  Software for displaying and exporting map tiles.
 * The sources and executables of MapVision software are available:
 *    - from project hosting on CodePlex.com :   http://mapvision.codeplex.com
 *    - from GIT repositories on Gitorious.org:  https://gitorious.org/mapvision
 * Visit MapVision fanpage on Facebook.com:      https://www.facebook.com/pages/Mapvision/631827753513935
 *
 * *********************************************************************************************************
*/

#include "layerimg.h"
#include <QTextStream>

LayerIMG::LayerIMG(QMainWindow *mainWindow_): Layer(mainWindow_)
{
    dialog = new DialogLayerIMG(mainWindow_,this);
    if (dialog->exec())
    {
        this->init();
    } else {
        this->deleteLater();
    }

}

LayerIMG::LayerIMG(QMainWindow *mainWindow_, Layer::layerType type_, QString name_, QString source_, QPointF lonlat_, int zoom_, int zValue_, int opacity_)
    : Layer(mainWindow_)
{

    setLayerType(type_);
    setLayerName(name_);
    setOrigin(lonlat_,zoom_);
    setOpacity(double(opacity_)/100.0);
    setSource(source_);
    setZvalue(zValue_);


    QString dirW = source_;
    dirW.remove(source_.size()-2,1);
    dirW+="w";
    if (loadWorldFileTiny(dirW)){
        ;
    } else {
        QMessageBox msgBox;
        msgBox.setText(tr("Worldfile is invalid or is missing!"));
        msgBox.exec();
        this->deleteLater();
        return;
    }

    if (getItems().size()==6){
        QPixmap img(0,0);
        if (!img.load(source_)  || img.height() == 0){
            QMessageBox msgBox;
            msgBox.setText(tr("Image was not loaded ! "));
            msgBox.exec();
            this->reject();
            return;
        }
        setIMG(img);
        processWorldFile();
    }

    this->init();
}

void LayerIMG::mapRectChanged(QRect rect, int zoom)
{

}

void LayerIMG::init()
{
    getMapScene()->addItem(layerGroup);
    initItem();
    connect(this,SIGNAL(zoomIsChanging(int)),this,SLOT(zoomHasChanged(int)));


    // insert item to layer list
    QListWidgetItem *item = new QListWidgetItem(this->getLayerName());
    item->setIcon(QIcon("images/buttons/layerIMG.svg"));
    item->setCheckState(Qt::Checked);
    item->setData(Qt::UserRole,getId());
    getListWidget()->insertItem(getZvalue(),item);

    setZvalue(this->getListWidget()->count()-1);

    layerGroup->setZValue(getZvalue());

    emit sendMessage("<code>"+tr("Layer ")+this->getLayerName()+tr(" was loaded!")+"</code><br>"  );

    getMapView()->refresh();
    getListWidget()->update();


}

bool LayerIMG::processWorldFile()
{
    scaleList.clear();

    if (worldfileItems[1] != 0 || worldfileItems[2]!=0) return false;

    refLonlat = QPointF(worldfileItems[4],worldfileItems[5]);


    QPointF imgSize(img.width(),img.height());


    QPointF imgRes(worldfileItems[0],worldfileItems[3]);

    QPointF second = QPointF(imgSize.x() * imgRes.x(),imgSize.y() * imgRes.y()) + refLonlat;

    refLonlat = zavaProj.UTM2lonlat(refLonlat);

    second = zavaProj.UTM2lonlat(second);

    originPoint2 = (refLonlat+second)/2;

    QPointF tlPixels = zavaProj.lonlat2pixels(refLonlat,20);
    QPointF bRPixels = zavaProj.lonlat2pixels(second,20);

    QPointF sizePixels = bRPixels-tlPixels;

    QPointF scale = QPointF(sizePixels.x()/img.width(),sizePixels.y()/img.height());

    double scaleD = (scale.x()+scale.y())/2;

    QList<double> scaleListTemp;

    for (int var = 20; var >= 0; var--) {
        scaleListTemp << scaleD;
        scaleD/=2.0;
    }

    for (int var = scaleListTemp.size()-1; var >=0 ; var--) {
        scaleList << scaleListTemp[var];
    }

    QList<double> tempList;
    foreach (double val, scaleList) {
        tempList << (1-val);
    }

    double temp = 999;
    for (int i = 0; i < tempList.size()-1; i++) {
        if (abs(tempList[i]) < temp){
            temp = tempList[i];
        }
    }

    originZoom2 = tempList.indexOf(temp);

    return true;
}

bool LayerIMG::loadWorldFileTiny(QString fileName)
{
    items.clear();
    worldfileItems.clear();
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) return false;

    QTextStream stream(&file);

    QString line = stream.readLine();


    while (!line.isNull()) {
        items << line;
        line = stream.readLine();
    }
    if (items.size()!=6) return false;

    foreach (QString item, items) {
        bool ok;
        double temp = item.toDouble(&ok);

        if (ok) worldfileItems << temp;
        else return false;

    }
    return true;
}

void LayerIMG::initItem()
{


    if (img.width()==0){
        QMessageBox msgBox;
        msgBox.setText(tr("Image is too big!"));
        msgBox.exec();
        this->deleteLater();
    }
    pixItem = new QGraphicsPixmapItem(img);
    pixItem->setTransformOriginPoint(0,0);
    layerGroup->addToGroup(pixItem);


}

void LayerIMG::zoomHasChanged(int zoom)
{
    if (isRendering()){
        pixItem->setScale(scaleList[zoom]);
        pixItem->setPos(zavaProj.lonlat2pixels(refLonlat,zoom));
    }

}


